<template>
  <el-dialog width="800" :title="titleDialog" v-model="visible" @close="onClose" draggable>
    <el-form :model="formParams" :rules="rules" ref="formRef" label-width="auto">
      <el-form-item label="活动名称: " prop="name">
        <el-input
          style="width: 200px"
          v-model.trim="formParams.name"
          placeholder="请输入活动名称"
          :disabled="titleDialog !== '新增'"
        />
      </el-form-item>
      <el-form-item v-show="titleDialog === '新增'" label="跳转页面URL: " prop="pageUrl">
        <el-input
          style="width: 200px"
          v-model.trim="formParams.pageUrl"
          placeholder="请输跳转页面URL"
        />
      </el-form-item>

      <el-form-item label="活动icon: " prop="imgUrl">
        <ImageUploadByType
          v-model="formParams.imgUrl"
          :isShowTip="false"
          uploadType="1"
          :limit="1"
          :fileSize="1"
          :imagePx="[96, 96]"
        />
        <div>图片比例为96px*96px，请上传 大小不超过 1MB 格式为 png/jpg/jpeg 的文件</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { postAddMiniJinGangApi, postUpdateMiniJinGangApi } from '@/api/marketing/activityControl'

const visible = ref(false)
const titleDialog = ref('新增')
const formRef = ref()
const formParams = ref({ name: null, imgUrl: null })
const rules = {
  name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  imgUrl: [{ required: true, message: '请选择活动图片', trigger: 'blur' }]
}

function handleAction(confirm) {
  if (confirm) {
    delete formParams.value?.loading
    const params = {
      ...formParams.value,
      imgUrl: formParams.value.imgUrl.length
        ? formParams.value.imgUrl[0].url
        : formParams.value.imgUrl
    }
    const Api =
      titleDialog.value === '新增'
        ? postAddMiniJinGangApi(params)
        : postUpdateMiniJinGangApi(params)

    Api.then(() => {
      emit('refreshList')
    })
  }
  visible.value = false
}

const emit = defineEmits(['refreshList'])
function onClose() {
  formRef.value.resetFields()
  formParams.value = { name: null, imgUrl: null }
  visible.value = false
}
function init(row) {
  if (row) {
    titleDialog.value = '编辑'
    formParams.value = { ...row }
  } else {
    titleDialog.value = '新增'
  }
  visible.value = true
}
defineExpose({
  init
})
</script>
<style lang="scss" scoped></style>
